<template>
  <div class="switch" @click="state = !state">
    <div class="switch-circle"></div>
  </div>
</template>

<script lang="ts">
import { ref, watch, defineProps, defineEmit, defineComponent } from 'vue';
import { primaryColor } from '@/config/layout.ts';

export default defineComponent({
  props: {
    modelValue: {
        type: Boolean,
        default: false
      },
      color: {
        type: String,
        default: primaryColor
      }
  },
  emits: ['update:modelValue', 'change'],
  setup(props, ctx) {
    const emit = ctx.emit;
    const state = ref(props.modelValue);
    const bg = ref('#dddee6');
    const left = ref('2px');
    watch(state, (v) => {
      bg.value = v ? props.color : '#dddee6';
      left.value = v ? '22px' : '2px';
      emit('update:modelValue', v);
      emit('change', v);
    }, { immediate: true });
    return {
      state,
      bg,
      left
    }
  }
})

</script>

<style scoped>
.switch {
  width: 40px;
  height: 20px;
  background-color: v-bind(bg);
  transition: all 0.25s ease-out;
  border-radius: 10px;
  position: relative;
  cursor: pointer;
}

.switch-circle {
  position: absolute;
  background-color: #fff;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  top: 2px;
  transition: left 0.25s ease-out;
  left: v-bind(left);
}
</style>